package com.shushan.shushanbao;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.umeng.message.UmengNotifyClickActivity;
import com.umeng.message.entity.UMessage;

import org.android.agoo.common.AgooConstants;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * @ClassName: MipushNotifyActivity
 * @Desciption: 小米、华为和魅族系统通道推送打开界面
 * @author: yichaohua
 * @date: 2018-06-28
 */
public class MipushNotifyActivity extends UmengNotifyClickActivity {

    private static final String TAG = "MipushNotifyActivity";

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            Intent intent = new Intent(MipushNotifyActivity.this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            addMessageToIntent(intent, (UMessage) msg.obj);

            startActivity(intent);

            finish();
        }
    };

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.splash_activity);
    }

    @Override
    public void onMessage(Intent intent) {
        super.onMessage(intent);  //此方法必须调用，否则无法统计打开数

        String body = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
        Log.i(TAG, body);

        try {
            JSONObject jsonObject = new JSONObject(body);
            UMessage uMessage = new UMessage(jsonObject);

            Message message = Message.obtain();
            message.obj = uMessage;
            handler.sendMessage(message);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void addMessageToIntent(Intent intent, UMessage msg) {

        if (intent == null || msg == null) {
            return;
        }

        intent.putExtra("afterOpen", msg.after_open);
        intent.putExtra("url", msg.url);
        intent.putExtra("activity", msg.activity);

        if(msg.extra != null){
            for (Map.Entry<String, String> entry : msg.extra.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (key != null) {
                    intent.putExtra(key, value);
                }
            }
        }

    }
}
